import { readFileSync, writeFileSync } from 'fs';

try {
  // 读取当前的.env文件
  let envContent = readFileSync('.env', 'utf8');
  
  console.log('🔍 当前.env文件内容预览:');
  console.log('旧HOST配置:', envContent.match(/HOST=.*/)?.[0] || '未找到HOST配置');
  
  // 新的ngrok URL
  const oldHost = 'aec273e4df7a.ngrok-free.app';
  const newHost = '464f65ee4326.ngrok-free.app';
  
  // 新的API配置
  const newApiKey = '92d1ae7d0a8c948327c7795b27a2518a';
  const newApiSecret = 'dc79705efdfc71c3b1ecb0a997b922d8';
  const newScopes = 'read_orders,write_orders,read_products,write_products,read_themes,write_themes';
  
  // 更新所有相关的配置
  envContent = envContent
    .replace(new RegExp(oldHost, 'g'), newHost)
    .replace(/HOST=.*$/m, `HOST=${newHost}`)
    .replace(/SHOPIFY_REDIRECT_URI=.*$/m, `SHOPIFY_REDIRECT_URI=https://${newHost}/api/auth/callback`)
    .replace(/SHOPIFY_API_KEY=.*$/m, `SHOPIFY_API_KEY=${newApiKey}`)
    .replace(/SHOPIFY_API_SECRET=.*$/m, `SHOPIFY_API_SECRET=${newApiSecret}`)
    .replace(/SHOPIFY_SCOPES=.*$/m, `SHOPIFY_SCOPES=${newScopes}`);
  
  // 写回文件
  writeFileSync('.env', envContent);
  
  console.log('\\n✅ 环境变量已更新');
  console.log('🔄 更新的配置:');
  console.log(`- HOST: ${newHost}`);
  console.log(`- SHOPIFY_API_KEY: ${newApiKey}`);
  console.log(`- SHOPIFY_API_SECRET: ${newApiSecret}`);
  console.log(`- SHOPIFY_SCOPES: ${newScopes}`);
  console.log(`- SHOPIFY_REDIRECT_URI: https://${newHost}/api/auth/callback`);
  console.log('\\n📝 Shopify Partners Dashboard配置:');
  console.log(`- App URL: https://${newHost}`);
  console.log(`- Allowed redirection URL: https://${newHost}/api/auth/callback`);
  console.log('\\n🎯 更新后的完整URL:');
  console.log(`- 应用访问地址: https://${newHost}`);
  console.log(`- OAuth测试地址: https://${newHost}?shop=kekudeshop.myshopify.com`);
  console.log(`\\n🔐 新的OAuth授权URL:`);
  console.log(`https://admin.shopify.com/store/kekudeshop/oauth/authorize?client_id=${newApiKey}&scope=${newScopes}&redirect_uri=https://${newHost}/api/auth/callback`);
  
} catch (error) {
  console.error('❌ 更新环境变量失败:', error.message);
  console.error('请确保.env文件存在于项目根目录');
}
